const utils = require('../../utils/util');
const Config = require('../../config.js');
const common = require('../common');
const { co } = require('../../helper');

const app = getApp();
const { apps, serverUrl, msUrls } = Config;

const reg = /^\w{1,15}$/;

let doLogin = false;

Page({
  data: {
    userId: '',
    isHiddenTip: true,
    apps,
    appkeys: apps.map(item => item.appkey),
    appkeyIndex: 0,
    msUrls: msUrls.map(item => item.title),
    msUrl: msUrls[0],
  },
  appkeyChange(e) {
    const appkeyIndex = parseInt(e.detail.value);
    this.setData({ appkeyIndex });
  },
  msUrlChange(e) {
    const index = parseInt(e.detail.value);
    this.setData({
      msUrl: msUrls[index],
    });
  },
  onInput (e) {
    let { detail: { value: userId } } = e;
    let isHiddenTip = reg.test(userId) || utils.isEmpty(userId)
    this.setData({
      userId,
      isHiddenTip
    });
  },
  async login () {
    if (doLogin) {
      return;
    }
    doLogin = true;
    let context = this;
    let { data: { userId, msUrl, appkeyIndex } } = context;
    let isUserEmpty = utils.isEmpty(userId);
    if (isUserEmpty) {
      context.setData({ isHiddenTip: !isUserEmpty });
      doLogin = false;
      return;
    }

    const { appkey, secret } = apps[appkeyIndex];
    
    wx.showLoading({ title: '登录中', mask: true })
    let result;
    try {
      result = await co(wx.request)({
        url: serverUrl,
        method: 'POST',
        data: {
          appkey,
          secret,
          userId,
          name: userId,
          portrait: `portrait-${userId}`,
        },
      });
    } catch (error) {
      doLogin = false;
      wx.hideLoading();
      common.showToast(`获取 Token 失败 ${error.statusCode}`);
      return;
    }

    wx.hideLoading();

    const { token, code, msg } = result.data;
    if (code !== 200) {
      console.error(code, msg);
      return;
    }

    app.setServiceConf(appkey, msUrl.url);

    wx.navigateTo({
      url: `../main/main?token=${encodeURIComponent(token)}&userId=${userId}&appkey=${appkey}`,
    });

    doLogin = false;
  }
})